package com.xzhuang.mq.common;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/***
 * 
 * @author zyf
 *
 */
public class RabbitConfig {
	
	//private static ResourceBundle bundle = ResourceBundle.getBundle("rabbit_config",Locale.getDefault());
	private static ConnectionFactory factory ;
	private static Connection connection ;
	
	public static ConnectionFactory getConnectionFactory() {
		if(factory == null) {
			factory = new ConnectionFactory();
//			factory.setHost(bundle.getString("mq.host"));
//			factory.setPort(Integer.parseInt(bundle.getString("mq.port")));
//			factory.setUsername(bundle.getString("mq.username"));
//			factory.setPassword(bundle.getString("mq.password"));
//			
//			factory.setHost("192.168.50.67");
//			factory.setPort(Integer.parseInt("5672"));
//			factory.setUsername("admin");
//			factory.setPassword("123");
//			
			factory.setHost("172.16.100.101");
			factory.setPort(Integer.parseInt("5672"));
			factory.setUsername("guest");
			factory.setPassword("guest");
			
			
			ExecutorService service = Executors.newFixedThreadPool(500);
			factory.setSharedExecutor(service);
			factory.setAutomaticRecoveryEnabled(true);
			factory.setConnectionTimeout(15000);// 15秒
			factory.setRequestedHeartbeat(60);
			return factory;
		}else {
			return factory;
		}
	}
	/***
	 *  zyf
	 * @param reSetConnection : 是否得到一个新的连接， MQ官方建议使用短连接，但是每次创建连接都需要消耗资源, 当 reSetConnection ：为FALSE的时候，使用之前创建的连接，
	 * 如果MQ为集群部署，则这个参数最好传TRUE， 每次从集群中不同的节点获取连接，
	 * 
	 * @return Connection
	 * @throws Exception
	 */
	public static Connection getConnection(boolean reSetConnection)throws TimeoutException,IOException{
		if(reSetConnection) {
			return getConnectionFactory().newConnection();
		}else {
			if(connection != null && connection.isOpen()) {
				return connection;
			}else {
				return getConnectionFactory().newConnection();
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
}
